# -*- coding: utf8 -*-

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

from setting import *


def draw_test(mode, i=0):
    i = 0
    if mode == GL_SELECT:
        glPushName(i)
        # glLoadName(i)
    glBegin(GL_TRIANGLES)
    glColor3f(1.0, 1.0, 0)
    glVertex3f(0.0+i, 1.0, 0.0)
    glVertex3f(1.0+i, -1.0, 0.0)
    glVertex3f(-1.0+i, -1.0, 0.0)
    glEnd()
    if mode == GL_SELECT:
        glPopName()


def pick(button, state, x, y):
    buffer_size = 512
    if button != GLUT_LEFT_BUTTON or state != GLUT_DOWN:
        return
    # 进入选择模式
    glSelectBuffer(buffer_size)   # 告诉OpenGL初始化buf
    glRenderMode(GL_SELECT)

    glMatrixMode(GL_PROJECTION)  # 进入投影阶段准备拾取
    glPushMatrix()
    glLoadIdentity()

    viewport = glGetIntegerv(GL_VIEWPORT)

    gluPickMatrix(x, (viewport[3] - y), 5, 5, viewport)
    gluPerspective(45.0, float(WINDOW_WIDTH) / float(WINDOW_HEIGHT), 0.1, 100.0)
    glMatrixMode(GL_MODELVIEW)
    glInitNames()   # 初始化名字栈
    glPushName(0)
    # 在x，y的位置产生一个5x5的选取框
    # glOrtho(-10, 10, -10, 10, -10, 10)

    # glPushName(1)   # 在名字栈中放入一个初始化名字，这里为'0'
    draw_test(GL_SELECT, 1)

    # 恢复投影
    glMatrixMode(GL_PROJECTION)
    glPopMatrix()
    glMatrixMode(GL_MODELVIEW)
    glFlush()

    hits = glRenderMode(GL_RENDER)  # 从选择模式返回正常模式,该函数返回选择到对象列表
    if len(hits) > 0:
        print u"鼠标点击：", hits[0].names[0]
    # processHits(hits, selectBuf)
    glutPostRedisplay()  # 标记当前窗口需要重新绘制